<?php
YII::import('dao.bid.*');
YII::import('dao.bidAuction.AuctionLimitDao');
YII::import('application.extensions.YiiMailer.YiiMailer');
class PaymentBuyAuction extends PaymentProcess {
	public $response;
	public $ffl;
	
    /**
     * Buy bidPack Auction ,add Bid ,add EarnbidLog
     */
	public function  buyBidpackAuction($bids=0,$bonusBid=0){
	    $bids=intval($bids);
	    $bonusBid=intval($bonusBid);
	    if ($bids>0 || $bonusBid>0){
	        $bid = new BidDao();
	        $bid->customerId=$this->customer->id;
	        if ($bids>0){
	            $bid->getBidModel('cash')->setEnv('parentTransaction');
	            $bid->getBidModel('cash')->setEnv('throw');
	            $bid->getBidModel('cash')->setBid($bids,'BUY_AUCTION');
	        }
	         
	        if ($bonusBid>0){
	            $bid->getBidModel('promo')->setEnv('parentTransaction');
	            $bid->getBidModel('promo')->setEnv('throw');
	            $bid->getBidModel('promo')->setBid($bonusBid,'BUY_AUCTION');
	        }
	         
	        $earnedbidlog=new EarnedBidLog();
	        $bidsNum=$bonusBid+$bids;
	        $earnedbidlog->customer_id=$this->customer->id;
	        $earnedbidlog->amount=$bidsNum;
	        $earnedbidlog->note="Buy bidPack Auction "." ".$bidsNum." Bids";
	        if($this->getPaymentInfo()->existence('buyItNow')){
	            $earnedbidlog->value=$this->auction->value_price;
	        }else{
    	        $earnedbidlog->value=$this->orderInfo->total_price;
	        }
	        $earnedbidlog->bid_pack_id=1;
	        $earnedbidlog->bid_source_type=1;//buy bid pack
	        $earnedbidlog->bid_type=1;//CASH bid
	        $earnedbidlog->created=time();
	        $earnedbidlog->save();
	    }    
	}
	
	public function save(){
		$db = Yii::app()->db->beginTransaction();
		$status = 5;
		$parentId = 0;
		$paymethod = 'Braintree';
		try{
		    $paymentMenthod = $this->getProcessInfo();
		    $paymentMenthodType = $paymentMenthod['paymentType'];
		    if($paymentMenthodType==2){
    			$billingId = $this->billingInfo->saveInfo();
    			$paymethod = 'AuthorizeNet';
		    }
			
			$packingtime = 0;
			$vendor = 0;
			if($this->getPaymentInfo()->existence('buyItNow')){
				$this->buyItNow->status = $status;
				$this->buyItNow->shipping_info = json_encode($this->shippingInfo->toArray());
				$this->buyItNow->paid_time = time();
				$this->buyItNow->modified = time();
				$this->buyItNow->payment_method = 2;
				$this->buyItNow->vendor_id = $this->getPaymentInfo()->buyItNow->vendor_id;
				$this->buyItNow->packing_time = $packingtime;
// 				$this->buyItNow->ffl = Yii::app()->cache->get('ffl'.Yii::app()->user->id);
				$this->buyItNow->saveInfo();
				//echo "<pre>";var_dump($this->buyItNow->id);die;
				$orderid = $this->buyItNow->id;
				
				/**
				 * Buy it now add Bids
				 */
				$auctionDao=new AuctionDao();
				$auctionDao->find($this->auction->id);

				if ($auctionDao->type==2 && $auctionDao->bids>0){
					$this->buyBidpackAuction($auctionDao->bids,$auctionDao->bonus_bid);
					$orders=new Orders();
					$orders=$orders->findByPk($orderid);
					$orders->status=6;
					$orders->save();
				}
				
				/**
				 * 保存giftcard相关信息
				 */
				 $paymentInfo=$this->getPaymentInfo();
				if(!empty($paymentInfo->giftCard)){
    				$orders=new Orders();
    				$orders=$orders->findByPk($orderid);
    				$orders->merchant_notes=1;
    				$orders->vendor_price=round($this->buyItNow->total_price*0.85,2);
    				$orders->save();
				} 
			
				
				$limit=new AuctionLimitDao();
				$limit->customerId=$this->customer->id;
				$limit->auctionId=$this->auction->id;
				$limit->add($this->auction->expires_time,'BUY_IT_NOW');
				$mailer = new YiiMailer();
				$customerinfo=Customer::model()->findByPk(Yii::app()->user->id);
				$mailer->setView('buy_it_now');//

				$mailer->setData(array(
				    'USER_NAME'=>Yii::app()->user->name,
				    'AUCTION_NAME'=>$this->auction->title,
				    'TOTAL_COST'=>$this->buyItNow->total_price,
					'TAX'		=>$this->buyItNow->tax_fee,
				    'CURRENT_PRICE'=>$this->buyItNow->price,
				    'SHIPPING_COSTS'=>$this->buyItNow->shipping_fee,
				    'URL'=>Yii::app()->baseUrl."/myaccount/wonauctions/".Yii::app()->user->id
				));//所需数据

				//发送到邮箱
				$mailer->AddAddress($customerinfo->email);//目标邮箱
				
				$mailer->Subject = Yii::t('demo', 'You have just purchased  '.$this->auction->title.'!');//标题
				if(!$mailer->Send()) {
				    echo "Mailer Error: " . $mailer->ErrorInfo;
				}
				$model = new PaymentLog();
				$model->type = 2;
				$model->request = $this->getPaymentCode();
				$model->customer_id = Yii::app()->user->id;
				$model->created = time();
				$model->response = $this->response;
				$model->order_id =$orderid;
				$model->object_type = 2;				
				
				$model->save();
				//发送邮件通知用户购买成功BUY IT NOW
				//时间，用户名，购买产品名称，BID次数，订单的各种费用，订单状态

				//duan start
				if ($auctionDao->type==2 && $auctionDao->bids>0){
					$mailer = new YiiMailer();
					$mailer->setView('shipped');//

					$mailer->setData(array(
							'USER_NAME'=>Yii::app()->user->name,
							'AUCTION_NAME'=>$this->auction->title,
							'WON_DATE'=> time(),
							'URL'=>Yii::app()->baseUrl."/myaccount/wonauctions/".Yii::app()->user->id
					));//所需数据

					//发送到邮箱
					$mailer->AddAddress($customerinfo->email);//目标邮箱

					$mailer->Subject = Yii::t('demo', 'Your winning item has shipped');//标题
					if(!$mailer->Send()) {
						echo "Mailer Error: " . $mailer->ErrorInfo;
					}
				}
				//duan end
			}else{
			    $this->buyBidpackAuction($this->auction->bid_pick_bids,$this->auction->bonus_bid);
				$this->orderInfo->status = 6;
				$this->orderInfo->shipping_info = json_encode($this->shippingInfo->toArray());
				$this->orderInfo->paid_time = time();
				$this->orderInfo->modified = time();
				$this->orderInfo->payment_method = 2;
// 				$this->orderInfo->vendor_id = $vendor;
				$this->orderInfo->packing_time = $packingtime;
// 				$this->orderInfo->ffl = Yii::app()->cache->get('ffl'.Yii::app()->user->id);
				$this->orderInfo->saveInfo();
				$orderid = $this->orderInfo->id;	
				
				/**
				 * 保存giftcard相关信息
				 */
				$paymentInfo=$this->getPaymentInfo();
				if(!empty($paymentInfo->giftCard)){
				    $orders=new Orders();
				    $orders=$orders->findByPk($orderid);
				    $orders->merchant_notes=1;
				    $orders->vendor_price=round($this->orderInfo->total_price*0.85,2);
				    $orders->save(); 
				}
				
				$mailer = new YiiMailer();
				$mailer->setView('win_auction');//调用模板
				$mailer->setData(array(
				    'USER_NAME'=>Yii::app()->user->name,
				    'AUCTION_NAME'=>$this->auction->title,
				    'TOTAL_COST'=>$this->orderInfo->total_price,
				    'CURRENT_PRICE'=>$this->orderInfo->price,
				    'SHIPPING_COSTS'=>$this->orderInfo->shipping_fee,
				    "URL"=>AuctionInfo::getDetailUrl($this->auction->title, $this->auction->id)
				));//所需数据
				//发送到邮箱
				$customerinfo=Customer::model()->findByPk(Yii::app()->user->id);
				$mailer->AddAddress($customerinfo->email);//目标邮箱
				
				$mailer->Subject = Yii::t('demo', 'You have won!!');//标题
				if(!$mailer->Send()) {
				    echo "Mailer Error: " . $mailer->ErrorInfo;
				}
				$model = new PaymentLog();
				$model->type = 2;
				$model->request = $this->getPaymentCode();
				$model->customer_id = Yii::app()->user->id;
				$model->created = time();
				$model->response = $this->response;
				$model->order_id =$orderid;
				$model->object_type = 2;
				$model->save();
				//发送邮件通知用户购买成功BUY AUCITON
				//时间，用户名，购买产品名称，BID次数，订单的各种费用，订单状态

				//duan start
				$mailer = new YiiMailer();
				$mailer->setView('shipped');//

				$mailer->setData(array(
						'USER_NAME'=>Yii::app()->user->name,
						'AUCTION_NAME'=>$this->auction->title,
						'WON_DATE'=> time(),
						'URL'=>Yii::app()->baseUrl."/myaccount/wonauctions/".Yii::app()->user->id
				));//所需数据

				//发送到邮箱
				$mailer->AddAddress($customerinfo->email);//目标邮箱

				$mailer->Subject = Yii::t('demo', 'Your winning item has shipped');//标题
				if(!$mailer->Send()) {
					echo "Mailer Error: " . $mailer->ErrorInfo;
				}
			}
			// duan end
			if ($this->getPaymentInfo()->existence(PaymentAmazonCard::NAME)) {
				$amazon = new PaymentReplaceAmazon($this->getPaymentInfo());
				$amazon->saveSelectAmazon();
				$this->auction->title = $this->amazoncard->amazoncardInfo()->title;
			}
// 			Yii::app()->cache->delete('ffl'.Yii::app()->user->id);
			$db->commit();
			$this->getPaymentInfo()->deleteCache();
			
		} catch (Exception $ex){
			$db->rollback();
			$model = new PaymentLog();
			$model->type = 2;
			$model->request = $this->getPaymentCode();
			$model->customer_id = Yii::app()->user->id;
			$model->created = time();
			$model->response = json_encode($ex->getMessage());
			$model->save();
			$this->redirect(Yii::app()->baseUrl);
		}
		return $this;
	}
	
	public function redirect(){
		Yii::app()->session['paymentSuccess'] = true;
		$orderid = is_object($this->orderInfo)?$this->orderInfo->id:$this->buyItNow->id;
 		Yii::app()->getRequest()->redirect(Yii::app()->createUrl('checkout/confirm/orderid/'.$orderid));
	}
}